package com.tsmti.system.service.impl;


import com.tsmti.core.common.service.impl.BaseServiceImpl;
import com.tsmti.core.common.query.data.Page;
import com.tsmti.core.common.query.data.PageImpl;
import com.tsmti.core.common.query.data.PageRequest;
import com.tsmti.core.common.query.data.Pageable;
import com.tsmti.core.util.IpUtils;
import com.tsmti.core.util.AbstractServletUtils;
import com.tsmti.system.entity.Principal;
import com.tsmti.system.entity.UserOnline;
import com.tsmti.system.service.UserOnlineService;
import com.tsmti.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Title：PimsSystem
 * Class：com.ts.sys.service.impl
 * Comapny:
 *
 * @author：zcw
 * @version：2.5 CreateTime：2018/1/17 16:53
 * Modify log:
 * Description：
 */
@Service("userOnlineService")
public class UserOnlineServiceImpl extends BaseServiceImpl<UserOnline> implements UserOnlineService {

    /**
     * 上线
     * @param userOnline
     */
    @Override
    public void online(UserOnline userOnline) {
        if (StringUtils.isEmpty(userOnline.getHost())) {
            String hostIp = IpUtils.getIpAddr(AbstractServletUtils.getRequest());
            userOnline.setHost(hostIp);
        }
        // 如果已经登录，则跳转到管理首页
        Principal principal = UserUtils.getPrincipal();
        userOnline.setUsername(principal.getUsername());
        userOnline.setUserId(principal.getId());
        UserOnline oldOnline = get(userOnline.getId());
        save(userOnline);
    }

    /**
     * 下线
     * @param sid
     */
    @Override
    public void offline(String sid) {
        UserOnline userOnline = get(sid);
        if (userOnline != null) {
            remove(userOnline);
        }
    }

    /**
     * 批量下线
     * @param needOfflineIdList
     */
    @Override
    public void batchOffline(List<?> needOfflineIdList) {
        removeAllById(needOfflineIdList);
    }

    /**
     * 无效的UserOnline
     * @param expiredDate
     * @param page
     * @param rows
     * @return
     */
    @Override
    public Page<UserOnline> findExpiredUserOnlineList(Date expiredDate, int page, int rows) {
        String hql = "from UserOnline o where o.lastAccessTime < ? order by o.lastAccessTime asc";
        Long total = countByHql("select count(*)  " + hql, expiredDate);
        Pageable pageable = new PageRequest(page, rows);
        List<UserOnline> content = findByHql(hql, expiredDate);
        return new PageImpl<UserOnline>(content, pageable, total);
    }
}
